package de.hypoport.einarbeitung.scrumspirit.helper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 * @see http://www.objectpartners.com/2010/11/09/unit-testing-your-persistence-tier-code/
 */
public class PersistenceHelper {

	private static final String PERSISTENCE_UNIT_NAME = "eclipseLinkMem";

	private static final EntityManager entityManager;
	static {
		entityManager = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME).createEntityManager();
	}

	public static EntityManager getEntityManager() {
		return entityManager;
  };

	public static void clearDatabase(String tableName) throws SQLException {

		entityManager.getTransaction().begin();
		java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
		Statement s = connection.createStatement();
		s.execute("SET DATABASE REFERENTIAL INTEGRITY FALSE");
		Set<String> tables = new HashSet<String>();
		ResultSet rs = s.executeQuery("select " + tableName + " from INFORMATION_SCHEMA.system_tables "
				+ "where table_type='TABLE' and table_schem='PUBLIC'");
		while (rs.next()) {
			if (!rs.getString(1).startsWith("DUAL_")) {
				tables.add(rs.getString(1));
			}
		}
		rs.close();
		for (String table : tables) {
			s.executeUpdate("DELETE FROM " + table);
		}
		s.execute("SET DATABASE REFERENTIAL INTEGRITY TRUE");
		entityManager.getTransaction().commit();
		s.close();
	}
}
